<?php
namespace app\index\controller;

use app\common\model\Fruit as FruitModel;
use app\common\model\FruitSell as FruitSellModel;
use app\common\model\UserWallet as UserWalletModel;

use app\common\component\user\UserWalletLogService;

class FruitBuy extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

    public function index() {
    	$userId = \think\Session::get('user_id');

		$this -> view -> assign('userWallet', UserWalletModel::get(['user_id' => $userId]));

		$this -> view -> assign('fruitSells', FruitSellModel::alias('f_s')
		-> join('league_user u', 'f_s.user_id = u.user_id')
		-> field(
			'f_s.fruit_sell_id, f_s.status, f_s.type, f_s.num, f_s.price, f_s.create_time, ' .
			'u.username'
		)
		-> where('f_s.status = 1 AND f_s.user_id != ' . $userId)
		-> order('f_s.fruit_sell_id ASC')
		-> paginate(15, false));

        return $this -> view -> fetch();
    }
	
	public function handleBuy() {
		$post = $this -> request -> post();
		$currentTime = time();
		$userId = \think\Session::get('user_id');
		$userName = \think\Session::get('user_name');

		$fruitSellModelGet = FruitSellModel::get(['fruit_sell_id' => $post['fruit_sell_id']]);
		if(!$fruitSellModelGet) {
			return ['code' => -1, 'message' => '您购买的果子不存在!'];
		}

		if($fruitSellModelGet -> getData('status') == 9) {
			return ['code' => -1, 'message' => '您购买的果子已被购买!'];
		}

		$userWalletModelGet = UserWalletModel::get(['user_id' => $userId]);

		if($fruitSellModelGet -> price > $userWalletModelGet -> money) {
			return ['code' => -1, 'message' => '您的金钱不足!'];
		}

		switch($fruitSellModelGet -> getData('type')) {
			case 2:
				$fruitLogClass = '\app\common\component\fruit\FruitSecondLogService';
		}

		\think\Db::startTrans();
		try{
			$fruitSellModelGet -> status = 9;
			if(!$fruitSellModelGet -> save()) {
				throw new \Exception('购买失败, fruitSellModelGet save');
			}

			if(!FruitModel::where('user_id', $userId) -> setInc('fruit_second_buy', $fruitSellModelGet -> num)) {
				throw new \Exception('购买失败, FruitModel setInc!');
			}

			$fruitLogServiceCreate = (new $fruitLogClass()) -> create([
				'user_id' => $userId,
				'type' => 4,
				'active' => 1,
				'price' => $fruitSellModelGet -> num,
				'create_time' => $currentTime,
				'remark' => '购买果子'
			]);
			if($fruitLogServiceCreate['code'] != 0) {
				throw new \Exception($fruitLogServiceCreate['message']);
			}

			$userWalletLogServiceCreate = (new UserWalletLogService()) -> create([
				'type' => 7,
				'active' => 0,
				'price' => $fruitSellModelGet -> price,
				'from_user_name' => $userName,
				'to_user_name' => $userName,
				'to_user_name_new_money' => $userWalletModelGet -> money - $fruitSellModelGet -> price,
				'to_user_name_old_money' => $userWalletModelGet -> money,
				'create_time' => $currentTime,
				'remark' => '购买果子',
				'is_state' => 1
			]);
			if($userWalletLogServiceCreate['code'] != 0) {
				throw new \Exception($userWalletLogServiceCreate['message']);
			}

			$userWalletModelGet -> money -= $fruitSellModelGet -> price;
			if(!$userWalletModelGet -> save()) {
				throw new \Exception('购买失败, UserWalletModel save!');
			}

			$userWalletModelGet2 = UserWalletModel::get(['user_id' => $fruitSellModelGet -> user_id]);
			
			$userGet = \app\common\model\User::get(['user_id' => $fruitSellModelGet -> user_id]);
			$userWalletLogServiceCreate2 = (new UserWalletLogService()) -> create([
				'type' => 7,
				'active' => 0,
				'price' => $fruitSellModelGet -> price,
				'from_user_name' => $userGet -> username,
				'to_user_name' => $userGet -> username,
				'to_user_name_new_money' => $userWalletModelGet2 -> money + $fruitSellModelGet -> price,
				'to_user_name_old_money' => $userWalletModelGet2 -> money,
				'create_time' => $currentTime,
				'remark' => '购买果子',
				'is_state' => 1
			]);
			if($userWalletLogServiceCreate2['code'] != 0) {
				throw new \Exception($userWalletLogServiceCreate2['message']);
			}

			$userWalletModelGet2 -> money += $fruitSellModelGet -> price;
			if(!$userWalletModelGet2 -> save()) {
				throw new \Exception('购买失败, userWalletModelGet2 save!');
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			return ['code' => -1, 'message' => $e -> getMessage()];
		}

		return ['code' => 0, 'message' => '成功'];
	}
}
?>